from django.shortcuts import render, redirect
from .models import *
from .my_forms import *


def book(request):
    """
    书籍列表
    :param request:
    :return:
    """
    book_list = Book.objects.all()
    return render(request, 'book_list.html', locals())


def book_add(request):
    """
    添加书籍
    博客中有详细from用法、原理
    :param request:
    :return:
    """
    if request.method == 'GET':
        form = BookForm()  # 初始化forms
        return render(request, 'book_add.html', locals())
    else:
        form = BookForm(request.POST)  # forms组件获取提交的内容
        if form.is_valid():  # 全部匹配正确
            print(form.cleaned_data)  # 取到全部键值对{'name': 'xxx', 'email': 'xxx'}

            title = form.cleaned_data.get('title')
            price = form.cleaned_data.get('price')
            date = form.cleaned_data.get('date')
            publish = form.cleaned_data.get('publish')
            authors = form.cleaned_data.get('authors')
            # 写入数据库
            book_obj = Book.objects.create(title=title, price=price, date=date, publish=publish)
            # 多对多的列表，要特定语法 带*
            book_obj.authors.add(*authors)
        return redirect('/book_list/')


def book_edit(request, edit_id):
    """
    修改书籍信息
    :param request:
    :param edit_id: 提交的修改id
    :return:
    """
    if request.method == 'GET':
        # 取到待修改的书籍并把现有信息传入修改页面
        form = BookForm()  # 初始化forms
        book_obj = Book.objects.filter(pk=edit_id).first()

        return render(request, 'book_edit.html', locals())
    else:
        title = request.POST.get('title')
        price = request.POST.get('price')
        date = request.POST.get('date')
        publish_id = request.POST.get('publish_id')
        author_id_list = request.POST.getlist('author_id_list')  # 获取列表必须用 getlist
        # 从新设定用set  set不需要用*号
        Book.objects.filter(pk=edit_id).update(title=title, price=price, date=date, publish_id=publish_id)
        edit_book_obj = Book.objects.filter(pk=edit_id).first()
        edit_book_obj.authors.set(author_id_list)
        return redirect('/book_list/')


def book_delete(request, delete_id):
    """
    删除书籍
    :param request:
    :param delete_id:要删除的书籍id
    :return:
    """
    book_obj = Book.objects.filter(pk=delete_id).first()
    book_obj.delete()
    return redirect('/book_list/')
